package com.order.model.sys;  

import java.io.UnsupportedEncodingException;
import java.util.List;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Model;
import com.order.shiro.ShiroUtils;
import com.order.utils.DateUtils;
import com.order.utils.JsonUtils;

/** 
 * @Title: SysRole.java 
 * @Package com.order.model.sys 
 * @Description: 后台系统角色
 * @author LinBo
 * @date 2014-3-27 下午11:38:19 
 */

@TableBind(tableName="sys_role", pkName="id")
public class SysRole extends Model<SysRole> {

	private static final long serialVersionUID = 1L;
	public static final SysRole dao = new SysRole();
	public static final String ID = "id";
	public static final String NAME = "name";
	public static final String INFO = "info";
	public static final String LAST_UPDATED_BY = "last_updated_by";
	public static final String LAST_UPDATE_DATE = "last_update_date";
	/** 
	* @Title: containRole 
	* @描述: 判断是否含有对应id的角色
	* @param roleid
	* @return   
	* boolean    
	* @throws 
	*/ 
	public static boolean containRole(String roleid) {
		if(dao.findById(roleid) != null){
			return true;
		}
		return false;
	}

	/** 
	* @Title: getJsonTree 
	* @描述: 拼接成json
	* @return   
	* String    
	* @throws 
	*/ 
	public String getJsonTree() {
		StringBuffer json = new StringBuffer("[{\"id\":\"0\",\"text\":\"所有角色\",icon: customers,\"children\":["); // 初始化根节点
		String sql = "select r.id, r.name from sys_role r";
		List<SysRole> role = SysRole.dao.find(sql);
		StringBuffer parent_json = new StringBuffer();
		if (role != null && role.size() > 0) {
			for (int i = 0; i < role.size(); i++) {
				parent_json.append("{\"id\":\""+ role.get(i).getNumber("ID").intValue()+ "\",");
				parent_json.append("\"text\":\""+ role.get(i).getStr("NAME").toString().trim()+ "\",icon: memeber,");
				parent_json.append("\"parentid\":\"0\"");
				parent_json.append("},");
			}
		} else {
			parent_json.append("},");
		}
		json.append(parent_json.toString());
		json = new StringBuffer(json.substring(0, json.length() - 1) + "]}]");
		return json.toString();
	}
	
	/** 
	* @Title: getObj 
	* @描述: json转对象
	* @param json
	* @return   
	* SysRole    
	* @throws 
	*/ 
	public SysRole getObj(String json){
		try {
			return this.setAttrs(JsonUtils.fastjson2Map(json));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return this;
	}

	/** 
	* @Title: mySave 
	* @描述: 保存
	* @return   
	* boolean    
	* @throws 
	*/ 
	public boolean mySave() {
		return this.set(LAST_UPDATED_BY, ShiroUtils.getUserId())
			.set(LAST_UPDATE_DATE, DateUtils.getNowTime())
			.save();
	}
}
  